package com.aizuda.easyManagerTool.controller;

import com.aizuda.easy.security.domain.Rep;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RequestMapping("public")
@RestController
@Slf4j
public class PublicController {

    @Value("${config.file.path}")
    private String localPath;
    @Value("${setting.terminal.fullPath}")
    private String publicPath;

    @PostMapping("/uploadLocal")
    public Rep<String> uploadLocal(@RequestParam("file") MultipartFile file) {
        try {
            String name = file.getOriginalFilename();
            String string = UUID.randomUUID().toString().replace("-", "");
            String local = localPath + string + (name.contains(".") ? name.substring(name.indexOf(".")): "");
            File fil = new File(local);
            FileUtils.copyInputStreamToFile(file.getInputStream(), fil);
            return Rep.ok(local);
        }catch (Exception e){
            log.error("上传失败 {}",e.getMessage());
        }
        return Rep.error(500,"上传失败");
    }

    @PostMapping("/uploadPublic")
    public Rep<String> uploadPublic(@RequestParam("file") MultipartFile file) {
        try {
            String name = file.getOriginalFilename();
            String string = UUID.randomUUID().toString().replace("-", "");
            String local = localPath + string + (name.contains(".") ? name.substring(name.indexOf(".")): "");
            String publicP = publicPath + string + name.substring(name.indexOf("."));
            File fil = new File(local);
            FileUtils.copyInputStreamToFile(file.getInputStream(), fil);
            return Rep.ok(publicP);
        }catch (Exception e){}
        return Rep.error(500,"上传失败");
    }

}
